package com.example.campuslink.commen.dialog

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.CountDownTimer
import android.telephony.SmsManager
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import com.example.campuslink.R
import com.example.campuslink.commen.core.CoreDialog
import com.example.campuslink.commen.db.userInfo.UserInfoDao
import com.example.campuslink.commen.db.userInfo.UserInfoData
import com.example.campuslink.commen.db.userInfo.UserInfoTable
import com.example.campuslink.commen.db.userNumber.UserNumberDao
import com.example.campuslink.commen.db.userNumber.UserNumberData
import com.example.campuslink.commen.db.userNumber.UserNumberTable
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.databinding.DialogRegisterBinding
import com.example.campuslink.ui.activity.SchoolChoiceActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Random
import java.util.regex.Pattern


class RegisterDialog : CoreDialog<DialogRegisterBinding>(R.layout.dialog_register) {
    private var verificationCode: Int = 0
    private var countDownTimer: CountDownTimer? = null

    // 使用 lateinit 替代懒加载
    private lateinit var userInfoDB: UserInfoData
    private lateinit var userInfoDao: UserInfoDao
    private lateinit var userNumberDB: UserNumberData
    private lateinit var userNumberDao: UserNumberDao
    private lateinit var registerNumber: String

    override fun onAttach(context: Context) {
        super.onAttach(context)
        userInfoDB = UserInfoData.getDatabase(context.applicationContext)
        userInfoDao = userInfoDB.userInfoDao()
        userNumberDB = UserNumberData.getDatabase(context.applicationContext)
        userNumberDao = userNumberDB.userNumberDao()
        registerNumber = Sp.getString(context, "registerNumber") ?: ""
    }

    private val requestPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted: Boolean ->
        if (isGranted) {

        } else {
            // 权限被拒绝，显示提示
            Toast.makeText(requireContext(), "需要短信权限才能发送验证码", Toast.LENGTH_LONG).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun setupViews() {
        binding.editTelNumber.setText(registerNumber)
        binding.btnSendCaptChe.setOnClickListener {
            introduceCaptChe()
        }
        binding.btnCancel.setOnClickListener {
            dismiss()
        }
        binding.btnConfirm.setOnClickListener {

            if (binding.editCaptChe.text.toString().toInt() == verificationCode) {
                register()

            } else {
                Toast.makeText(context, "验证码错误", Toast.LENGTH_SHORT).show()
            }
        }
        binding.editCaptChe.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(p0: Editable?) {
                binding.btnConfirm.isEnabled = p0.toString().length == 4
            }
        })

    }

    fun register() {
        lifecycleScope.launch {
            try {
                lifecycleScope.launch(Dispatchers.IO) {
                    val userNumberInfo = UserNumberTable()
                    val telNumber = binding.editTelNumber.text.toString().trim()
                    if (userNumberDao.getUserNumber(telNumber) != null) {
                        lifecycleScope.launch(Dispatchers.Main) {
                            Toast.makeText(requireContext(), "该手机号已被注册", Toast.LENGTH_SHORT)
                                .show()
                        }
                    } else {
                        val password = "123456"
                        val data = System.currentTimeMillis()
                        userNumberInfo.telNumber = telNumber
                        userNumberInfo.password = password
                        userNumberInfo.createTime = data
                        val userInfoTable = UserInfoTable()
                        userInfoTable.userNumber = telNumber
                        userInfoTable.userName = "平台用户:${telNumber}"
                        userNumberInfo.userInfoData = userInfoTable
                        userNumberDao.insertUserNumber(userNumberInfo)
                        userInfoDao.insertUserInfo(userInfoTable)
                        lifecycleScope.launch(Dispatchers.Main) {
                            Sp.setString(
                                requireContext(),
                                "userNumber",
                                binding.editTelNumber.text.toString()
                            )
                            Sp.setString(
                                requireContext(),
                                "registerNumber",
                                ""
                            )
                            Toast.makeText(context, "注册成功!", Toast.LENGTH_SHORT).show()
                            dismiss()
                        }
                    }

                }


            } catch (e: Exception) {
                Log.i("TAG", "register: ${e.message}")
                lifecycleScope.launch(Dispatchers.Main) {
                    Toast.makeText(context, "注册失败: ${e.message}", Toast.LENGTH_SHORT).show()
                }

            }
        }
    }

    override fun createBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): DialogRegisterBinding {
        return DialogRegisterBinding.inflate(inflater, container, false)
    }


    private fun introduceCaptChe() {
        binding.run {
            val phoneNumber = editTelNumber.text.toString().trim()

            // 手机号验证（正则匹配）
            if (!isValidPhoneNumber(phoneNumber)) {
                Toast.makeText(context, "请输入正确的手机号码", Toast.LENGTH_SHORT).show()
                return
            }

            verificationCode = generateVerificationCode()
            Toast.makeText(context,  "您的验证码：$verificationCode，5分钟内有效", Toast.LENGTH_SHORT).show()
            startCountDown()
        }
    }

    private fun sendSms(phoneNumber: String, code: Int) {
        try {
            SmsManager.getDefault().sendTextMessage(
                phoneNumber,
                null,
                "您的验证码：$code，5分钟内有效",
                null,
                null
            )
            // TODO: 针对比我现在手机Android 版本更改无法产生Sms发送的dialog 这里用toast做模拟
            Toast.makeText(context, "验证码已发送,您的验证码：$code，5分钟内有效", Toast.LENGTH_SHORT)
                .show()
//            Toast.makeText(context, "验证码已发送", Toast.LENGTH_SHORT).show()
        } catch (e: Exception) {
            Log.i("TAG", "sendSms: " + e.message)
            Toast.makeText(context, "短信发送失败: ${e.message}", Toast.LENGTH_SHORT).show()
            e.printStackTrace()
        }
    }

    // 手机号验证（11位中国号段）
    private fun isValidPhoneNumber(phone: String): Boolean {
        return Pattern.matches("^1[3-9]\\d{9}$", phone)
    }

    // 生成4位数字验证码
    private fun generateVerificationCode(): Int {
        return Random().nextInt(9000) + 1000  // 1000-9999
    }

    private fun startCountDown() {
        binding.btnSendCaptChe.isEnabled = false  // 禁用按钮

        countDownTimer = object : CountDownTimer(60000, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                binding.btnSendCaptChe.text = "${millisUntilFinished / 1000}秒后重发"
            }

            override fun onFinish() {
                binding.btnSendCaptChe.isEnabled = true
                binding.btnSendCaptChe.text = "发送验证码"
            }
        }.start()
    }

    override fun onDestroy() {
        countDownTimer?.cancel()
        super.onDestroy()
    }
}